package cn.lbwfree.web.service.impl;

import cn.lbwfree.web.entity.Book;
import cn.lbwfree.web.entity.Borrow;
import cn.lbwfree.web.repository.BookRepository;
import cn.lbwfree.web.repository.BorrowRepository;
import cn.lbwfree.web.repository.impl.BookRepositoryImpl;
import cn.lbwfree.web.repository.impl.BorrowRepositoryImpl;
import cn.lbwfree.web.service.BookService;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class BookServiceImpl implements BookService {

    private BookRepository bookRepository = new BookRepositoryImpl();
    private BorrowRepository borrowRepository =new BorrowRepositoryImpl();
    private final int LIMIT = 6;
    @Override
    public List<Book> findAll(int page) {
        int index = (page-1)*LIMIT;
        return bookRepository.findAll(index ,LIMIT);
    }

    @Override
    public int getPages() {
        int count = bookRepository.count();
        int page =0;
        if(count % LIMIT == 0) {
            page = count / LIMIT;
        }else{
            page = count/LIMIT+1;
        }
        return page;
    }

    @Override
    public int getBorrowPages(Integer readerid) {
        int count = borrowRepository.count(readerid);
        int page =0;
        if(count%LIMIT==0){
            page = count/LIMIT;
        }else{
            page = count/LIMIT+1;
        }
        return page;
    }

    @Override
    public void addBorrow(Integer bookid, Integer readerid) {
        //借书事件
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String borrowTime = simpleDateFormat.format(date);
        //借书一个月
        Calendar calendar = Calendar.getInstance();
        int dates = calendar.get(Calendar.DAY_OF_YEAR)+14;
        calendar.set(Calendar.DAY_OF_YEAR, dates);
        Date date1 = calendar.getTime();
        String retuentime = simpleDateFormat.format(date1);
        borrowRepository.insert(bookid, readerid, borrowTime, retuentime, null, 0);
    }

    @Override
    public List<Borrow> findAllBorrowByReaderId(Integer id, Integer page) {
        // 将page 变成 index , limit
        int index = (page-1)*LIMIT;
        return borrowRepository.findAllByReaderId(id, index, LIMIT);
    }

    @Override
    public List<Borrow> findAllBorrowByState(Integer state, Integer page) {
        //分页处理借书页数
        int index =(page-1)*LIMIT;
        return borrowRepository.findAllByState(state, index, LIMIT);
    }

    @Override
    public int getBorrowPagesByState(Integer state) {
        //获取借书的页数
        int count = borrowRepository.countByState(state);
        int page =0;
        if(count%LIMIT==0){
            page = count/LIMIT;
        }else{
            page=count/LIMIT+1;
        }
        return page;
    }

    @Override
    public void handleBorrow(Integer borrowId, Integer state, Integer admind) {
        // 管理员处理借书
        borrowRepository.handle(borrowId, state, admind);
    }
}
